'use strict';

const Controller = require('egg').Controller;

class AddCartController extends Controller {
  async index() {
    const { ctx } = this;
    var {userName , commodity} = ctx.request.body
    commodity.num = 1;
    commodity.isSelected = true;
    var db = this.app.mongodb
    var res =await db.collection("user-cart").find({userName}).toArray()
    if(res.length){
      await db.collection("user-cart").update({userName},{$push :{cart:commodity}})
      ctx.body={
        code:200,
        msg:'添加成功'
      }
    }else{
      await db.collection("user-cart").insertOne({userName,cart:[]})
      await db.collection("user-cart").update({userName},{$push:{cart:commodity}})
      ctx.body={
        code:200,
        msg:'添加成功'
      }
    }
  }
}

module.exports = AddCartController;
